import React, { Component } from 'react'
import u from '../../common.js'
import echarts from 'echarts'
import { DatePicker } from 'antd';
import moment from 'moment';
import '../../static/dataStyle/dataStatistics.less'
const RangePicker = DatePicker.RangePicker;

class DataStatistics extends Component{
  constructor(props) {
    super(props)
    this.state = {
      list: [
      {
        name: '研判数据总量',
        num: null,
      },{
        name: '疑似舆情研判',
        num: null,
      },{
        name: '疑似情报研判',
        num: null,
      },{
        name: '疑似案件研判',
        num: null,
      }],
      hours: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24],
      dateNum: 1,
      openidList: [],
      idList: [],
      focusGroupTotal: null,
      focusMemberTotal: null,
      friendTotal: null,
      groupTotal: null,
      historyTotal: null,
      publicTotal: null,
      keyWordHistoryTotal: null,
      docCountList: [],
      docCountTotalList: [],
      morendata: ['2:00', '4:00', '6:00', '8:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00', '24:00'],
      timeStr: '',
      dayStr: '',
      weekStr: ''
    }
  }

  componentDidMount() {
    // 今日
    var date = new Date()
    var week = new Date().getDay()
    var year = date.getFullYear()
    let month = date.getMonth() + 1
    let day = date.getDate()
    let newTime = year + '-' + month + '-' + day + ' ' + '00:00:00'
    let timeList = []

    var dayList = []
    for (var i = 0; i < this.state.hours.length; i++) {
      if (this.state.hours[i] < 10) {
        let dayTime = '' + year + '-' + month + '-' + day + ' 0' + this.state.hours[i] + ':00:00'
        // alert((new Date(dayTime)).getTime())
        dayList.push((new Date(dayTime)).getTime())
      } else {
        let dayTime = '' + year + '-' + month + '-' + day + ' ' + this.state.hours[i] + ':00:00'
        dayList.push((new Date(dayTime)).getTime())
      }
    }
    var timeStr = ''
    for (var i = 0; i < dayList.length - 1; i++) {
      timeStr = timeStr + dayList[i] + '-' + dayList[i + 1] + ','
    }
    timeStr = timeStr.substring(0, timeStr.length - 1)
    console.log(timeStr)

    u.shujutongji({
      "aggsNumbers":"webSiteType",
      "aggsField": "addTime",
      "aggsType": "range",
      "aggsTerms":"terms",
      "isNeedUserKey": true,
      "ranges": timeStr
    },data =>{
      let list = []
      let listTotal = []
      data.data.forEach(el => {
        list.push(el.docCount)
        listTotal.push(el.docCountTotal)
      })
      this.setState({
        docCountList: list,
        docCountTotalList: listTotal
      },() => {
        this.onLeftChat(this.state.morendata,this.state.docCountList,this.state.docCountTotalList)
      })
    })

    // 本周
    for (var i = 0; i < week; i++) {
      let time = new Date(Date.parse(newTime) - 86400 * i * 1000)
      var y = time.getFullYear();
      var m = time.getMonth() + 1;
      var d = time.getDate();
      let week = '' + y + '-' + m + '-' + d + ' 00:00:00'

      timeList.push((new Date(week)).getTime())
    }
    if (7 - week > 0) {
      for (var j = 1; j <= (7 - week); j++) {

        let time = new Date(Date.parse(newTime) + 86400 * j * 1000)
        var y = time.getFullYear();
        var m = time.getMonth() + 1;
        var d = time.getDate();
        let week = '' + y + '-' + m + '-' + d + ' 00:00:00'

        timeList.push((new Date(week)).getTime())
      }
    }
    let timeArray = timeList.sort()
    var str = ''
    for (var i = 0; i < timeArray.length - 1; i++) {
      str = str + timeArray[i] + '-' + timeArray[i + 1] + ','
    }
    let dayStr = str.substring(0, str.length - 1)
    console.log(dayStr)

    // 本月
    let weeKList = []
    var count = 0
    for (var j = 0; j < 8; j++) {
      if (j === 0) {
        count = 0
        onWeek(count)
      }
      if (j != 0 && j % 2 === 0) {
        count = count + 1
        onWeek(count)
      }
      if (j != 0 && j % 2 !== 0) {
        count = count + 6
        onWeek(count)
      }
    }
    function onWeek(count) {
      let timeWeek = new Date(Date.parse(newTime) - 86400 * (week + count) * 1000)
      var y2 = timeWeek.getFullYear();
      var m2 = (timeWeek.getMonth() + 1) <= 9 ? '0' + (timeWeek.getMonth() + 1) : timeWeek.getMonth() + 1
      var d2 = timeWeek.getDate() <= 9 ? '0' + timeWeek.getDate() : timeWeek.getDate()
      let weekDay = '' + y2 + '-' + m2 + '-' + d2 + ' 00:00:00'
      weeKList.push((new Date(weekDay)).getTime())
    }
    var weekArray = weeKList.sort()
    var weekStr = ''
    for (var i = 0; i < weekArray.length / 2; i++) {
      weekStr = weekStr + weekArray[i * 2] + '-' + weekArray[i * 2 + 1] + ','
    }
    weekStr = weekStr.substring(0, weekStr.length - 1)
    console.log(weekStr)

    this.setState({
      timeStr: timeStr,
      dayStr: dayStr,
      weekStr: weekStr
    })
    
    u.dataStatistics({
      aggsType:"terms",
      aggsField:"judgeType",
      judgeType:'all',
      aggsSize:20,
      size:0,
    }, data => {
      let list = this.state.list
      list[0].num = data.total
      data.aggs.forEach((el,index) =>{
        list[index + 1].num = el.count
      })
      this.setState({
        list: list
      })
      this.onFirstEcharts(data.aggs,data.total)
    });
    
    u.dataCircle({
      "isNeedUserKey":true,
      "aggsField":"webSiteType",
      "aggsType":"terms"
    },data => {
      this.onleftChatBottomleft(data.collectTotal.total)
      this.onleftChatBottomright(data.clearTotal.total)
    })

    let userId = localStorage.getItem('userId')
    u.yiguanzhu({
      userId: userId
    },data =>{
      let list = []
      console.log(data)
      data.forEach(el =>{
        if (el.group_openId !== null) {
          list.push(el.group_openId)
        }
      })
      this.setState({
        openidList: list
      }, () =>{
        u.getMainList({
          userId: userId
        },data =>{
          let list2 = []
          data.forEach(el =>{
            list2.push(el.id + '')
          })
          this.setState({
            idList: list2
          },() =>{
            let focusGroup = this.state.openidList
            let focusMember = this.state.idList
            u.friendDate({
              "webSiteType" : "14",
              "focusGroup" : focusGroup,
              "focusMember": focusMember  
            },data => {
              this.setState({
                focusGroupTotal: data.focusHistoryTotal.focusGroupTotal,
                focusMemberTotal: data.focusHistoryTotal.focusMemberTotal,
                friendTotal: data.historyTotal.friendTotal,
                groupTotal: data.historyTotal.groupTotal,
                historyTotal: data.historyTotal.historyTotal,
                publicTotal: data.historyTotal.publicTotal,
                keyWordHistoryTotal: data.keyWordHistoryTotal
              },() =>{
                this.onrightChatBottom(this.state.groupTotal,this.state.friendTotal,this.state.publicTotal,this.state.historyTotal)
                this.onrightChatTop(this.state.historyTotal,this.state.keyWordHistoryTotal)
              })
            })
          })
        })
      })
    })

    // setTimeout(() =>{
    //   this.onLeftChat()
    // },200)
  }

  onChoseDate(num) {
    if (num === 1) {
      this.setState({
        morendata: ['2:00', '4:00', '6:00', '8:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00', '24:00'],
      },() =>{
        this.getChange(this.state.timeStr)
      })
    }
    if (num === 2) {
      this.setState({
        morendata: ['周一','周二','周三','周四','周五','周六','周日'],
      },() => {
        this.getChange(this.state.dayStr)
      })
    }
    if (num === 3) {
      this.setState({
        morendata: ['第一周','第二周','第三周','第四周'],
      },() => {
        this.getChange(this.state.weekStr)
      })
    }
    this.setState({
      dateNum: num
    })
  }

  getChange(timeDate) {
    u.shujutongji({
      "aggsNumbers":"webSiteType",
      "aggsField": "addTime",
      "aggsType": "range",
      "aggsTerms":"terms",
      "isNeedUserKey": true,
      "ranges": timeDate
    },data =>{
      let list = []
      let listTotal = []
      data.data.forEach(el => {
        list.push(el.docCount)
        listTotal.push(el.docCountTotal)
      })
      this.setState({
        docCountList: list,
        docCountTotalList: listTotal
      },() => {
        this.onLeftChat(this.state.morendata,this.state.docCountList,this.state.docCountTotalList)
      })
    })
  }

  onFirstEcharts = async (num,total) => {
    let firstChart = echarts.init(document.getElementById('firstEcharts'))
    var option = {
      title: [{
        text: total,
          x: '45%',
          y: '40%',
          textStyle: {
              fontWeight: 'normal',
              color: '#3f484f',
              fontSize: '22'
          }

      },{
        text: '总量',
          x: '46%',
          y: '51%',
          textStyle: {
              fontWeight: 'normal',
              color: '#9aaebf',
              fontSize: '14'
          }

      }],
      tooltip : {
          trigger: 'item',
          formatter: "{a} <br/>{b} : {c} ({d}%)"
      },
      calculable : true,
      series : [
          {
              name:'',
              type:'pie',
              radius : [55, 90],
              center : ['50%', '50%'],
              label: {
                normal: {
                  formatter: '{b} {per|{d}%}',
                  rich: {
                    per: {
                      color: '#768a99',
                      backgroundColor: 'white',
                      padding: [2, 4],
                      borderRadius: 2
                    }
                  },
                  textStyle:{
                    color:'#768a99',
                    fontSize:'14'
                  },
                }
              },
              data:[
                  {value:num[0].count, name:'舆情',itemStyle: {color: '#5ad354'}},
                  {value:num[1].count, name:'案件',itemStyle: {color: '#5286ff'}},
                  {value:num[2].count, name:'情报',itemStyle: {color: '#f9ab22'}},
              ],
              itemStyle: {
                emphasis: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
            }
          }
      ]
  };
  firstChart.setOption(option);
  }

  onrightChatTop = async (total,keyNum) => {
    let firstChart = echarts.init(document.getElementById('bottomRightTop'))
    var option = {
      title: [
        {
        text: (keyNum/total).toFixed(3) * 100 + '%',
          x: '33%',
          y: '38%',
          textStyle: {
              fontWeight: 'normal',
              color: '#3f484f',
              fontSize: '20'
          }

      },
      {
        text: '清洗占比',
          x: '33%',
          y: '54%',
          textStyle: {
              fontWeight: 'normal',
              color: '#9aaebf',
              fontSize: '13'
          }

      }],
      // tooltip : {
      //     trigger: 'item',
      //     formatter: "{a} <br/>{b} : {c} ({d}%)"
      // },
      // calculable : true,
      series : [
          {
              name:'',
              type:'pie',
              radius : [35, 60],
              center : ['45%', '50%'],
              label: {
                normal: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    show: false,
                    textStyle: {
                        fontSize: '15',
                        fontWeight: 'bold'
                    }
                }
              },
              labelLine: {
                  normal: {
                      show: false
                  }
              },
              data:[
                  {value: keyNum , name:'舆情',itemStyle: {color: '#5286ff'}},
                  {value: total - keyNum, name:'案件',itemStyle: {color: '#cccccc'}},
              ],
              itemStyle: {
                emphasis: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
            }
          }
      ]
    };
    firstChart.setOption(option);
  }

  onrightChatBottom = async (num1,num2,num3,total) => {
    let firstChart = echarts.init(document.getElementById('bottomRightBottom'))
    var option = {
      title: [
        {
        text: total,
          x: '44%',
          y: '40%',
          textStyle: {
              fontWeight: 'normal',
              color: '#3f484f',
              fontSize: '22'
          }

      },
      {
        text: '微信总量',
          x: '44%',
          y: '54%',
          textStyle: {
              fontWeight: 'normal',
              color: '#9aaebf',
              fontSize: '14'
          }

      }],
      tooltip : {
          trigger: 'item',
          formatter: "{a} <br/>{b} : {c} ({d}%)"
      },
      calculable : true,
      series : [
          {
              name:'',
              type:'pie',
              radius : [40,65],
              center : ['50%', '55%'],
              label: {
                normal: {
                  formatter: '{b} {per|{d}%}',
                  rich: {
                    per: {
                      color: '#768a99',
                      backgroundColor: 'white',
                      padding: [2, 4],
                      borderRadius: 2
                    }
                  },
                  textStyle:{
                    color:'#768a99',
                    fontSize:'14'
                  },
                }
              },
              data:[
                  {value: num3, name:'公众号',itemStyle: {color: '#5286ff'}},
                  {value: num2, name:'朋友圈',itemStyle: {color: '#f9ab22'}},
                  {value: num1, name:'微信群',itemStyle: {color: '#5ad354'}},
              ],
              itemStyle: {
                emphasis: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
            }
          }
      ]
    };
    firstChart.setOption(option);
  }

  onleftChatBottomleft = async (list) => {
    let firstChart = echarts.init(document.getElementById('left_bottom_left'))
    var option = {
      title: [
        {
          text: '采集占比',
          x: '43.5%',
          y: '47%',
          textStyle: {
            fontWeight: 'normal',
            color: '#9aaebf',
            fontSize: '14'
        }
        }],
        tooltip: {
            trigger: 'item',
            formatter: "{a} <br/>{b}: {c} ({d}%)"
        },
        series: [
            {
                name:'采集占比',
                type:'pie',
                center : ['50%', '52%'],
                radius: ['40%', '60%'],
                label: {
                  normal: {
                    formatter: '{b} {per|{d}%}',
                    rich: {
                      per: {
                        color: '#768a99',
                        backgroundColor: 'white',
                        padding: [2, 4],
                        borderRadius: 2
                      }
                    },
                    textStyle:{
                      color:'#768a99',
                      fontSize:'14'
                    },
                  }
                },
                data:[
                    {value:list[0], name:'新闻',itemStyle: {color: '#f9ab22'}},
                    {value:list[1], name:'论坛',itemStyle: {color: '#556bfe'}},
                    {value:list[2], name:'平面媒体',itemStyle: {color: '#15cd96'}},
                    {value:list[3], name:'博客',itemStyle: {color: '#54ced3'}},
                    {value:list[4], name:'贴吧',itemStyle: {color: '#3385ff'}},
                    {value:list[5], name:'热点新闻',itemStyle: {color: '#ff526f'}},
                    {value:list[6], name:'外文网站',itemStyle: {color: '#54ced3'}},
                ]
            }
        ]
    };
    firstChart.setOption(option);
  }

  onleftChatBottomright = async (list) => {
    let firstChart = echarts.init(document.getElementById('left_bottom_right'))
    var option = {
      title: [
        {
          text: '清洗占比',
          x: '43.5%',
          y: '45%',
          textStyle: {
            fontWeight: 'normal',
            color: '#9aaebf',
            fontSize: '14'
        }
        }],
      tooltip: {
          trigger: 'item',
          formatter: "{a} <br/>{b}: {c} ({d}%)"
      },
      series: [
          {
              name:'',
              type:'pie',
              center : ['50%', '50%'],
              radius: ['40%', '60%'],
              label: {
                normal: {
                  formatter: '{b} {per|{d}%}',
                  rich: {
                    per: {
                      color: '#768a99',
                      backgroundColor: 'white',
                      padding: [2, 4],
                      borderRadius: 2
                    }
                  },
                  textStyle:{
                    color:'#768a99',
                    fontSize:'14'
                  },
                }
              },
              data:[
                  {value:list[0], name:'新闻',itemStyle: {color: '#f9ab22'}},
                  {value:list[1], name:'论坛',itemStyle: {color: '#556bfe'}},
                  {value:list[2], name:'平面媒体',itemStyle: {color: '#15cd96'}},
                  {value:list[3], name:'博客',itemStyle: {color: '#54ced3'}},
                  {value:list[4], name:'贴吧',itemStyle: {color: '#3385ff'}},
                  {value:list[5], name:'热点新闻',itemStyle: {color: '#ff526f'}},
                  {value:list[6], name:'外文网站',itemStyle: {color: '#54ced3'}},
              ]
          }
      ]
  };
    firstChart.setOption(option);
  }

  onLeftChat = async (morendata,docCount,docCountTotal) => {
    let leftTop = echarts.init(document.getElementById('left_top_chart'))
    var option = {
      color: ['#3398DB'],
      tooltip : {
          trigger: 'axis',
          axisPointer : {            // 坐标轴指示器，坐标轴触发有效
              type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
          }
      },
      grid: {
          top: '5%',
          left: '5%',
          right: '5%',
          bottom: '5%',
          containLabel: true
      },
      xAxis : [
          {
              type : 'category',
              data: morendata,
              axisTick: {
                  alignWithLabel: true
              }
          }
      ],
      // yAxis : [
      //     {
      //         type : 'value'
      //     }
      // ],
      yAxis: [
        {
          type: 'value',
          splitNumber:4,
          axisTick: {
            show: false
          },
          axisLabel: {
            color: "#a1a5b5"
          },
          axisLine: {
            show: false
          },
          splitLine: {
            lineStyle: {
              type: "dashed",
            }
          }
         
        }
      ],
      series : [
          {
            name: '总量',
            type: 'bar',
            stack:'使用情况',
            data: docCountTotal,
            itemStyle:{
              normal:{color:"#537afe"},
                 
            },
            barWidth: '30%',
        },{
            name: '预警',
            type: 'bar',
            stack:'使用情况',
            data: docCount,
            itemStyle:{
              normal:{color:"#f98b16"},
            },
            barWidth: '30%',
        }
      ]
  };
    leftTop.setOption(option);
  }

  onChangeDate(dates, dateStrings) {
    console.log('From: ', dates[0], ', to: ', dates[1]);
    console.log('From: ', dateStrings[0], ', to: ', dateStrings[1]);
  }

  render() {
    return (
      <div className='dataStatistics'>

        <div className='data_title'>
          <div className='data_title_left'>
            <div className='title_top'>研判数据</div>
            <div className='title_box'>
            {
              this.state.list.map((el,index) =>{
                return(
                  <div className={'boxStyle' + ' ' + 'bg' + index}>
                    <span className='totalNumStyle'>{ el.num ? el.num : 0 }</span>
                    <span className='totalFont'>{ el.name }</span>
                  </div>
                )
              })
            }
            </div>
          </div>
          <div id='firstEcharts' className='data_title_right'></div>
        </div>

        <div className='data_content'>
          <div className='data_left'>
            <div className='data_left_top'>
              <div className='data_left_top_box'>
                <div className='data_left_top_title'>清洗数据</div>
                <div className='data_left_top_biaoge'>
                  <div className='clearData'>单位：条<span></span>清洗后数据</div>
                  <div className='choseChange'>
                    <div onClick={this.onChoseDate.bind(this,1)} className={this.state.dateNum === 1?'riqiChose riqiActive':'riqiChose'}>今日</div>
                    <div onClick={this.onChoseDate.bind(this,2)} className={this.state.dateNum === 2?'riqiChose riqiActive':'riqiChose'}>本周</div>
                    <div onClick={this.onChoseDate.bind(this,3)} className={this.state.dateNum === 3?'riqiChose riqiActive':'riqiChose'}>历时四周</div>
                  </div>
                </div>
              </div>
              <div id='left_top_chart' className='table_Style_table'></div>
            </div>
            <div className='data_left_bottom'>
              <div id='left_bottom_left' className='data_left_bottom_left'></div>
              <div id='left_bottom_right' className='data_left_bottom_right'></div>
            </div>
          </div>
          <div className='data_right'>
            <div className='right_box right_title'>
              微信数据
            </div>
            <div className='right_box right_one'>
              <div id='bottomRightTop' className='tu1'></div>
              <div className='right_total'>
                <div className='rightStyle rightStyleOne'>
                  <span>数据总采集量</span><br />
                  <span className='numStyle numStyleOne'>{this.state.historyTotal}</span>条<br />
                </div>
                <div className='rightStyle'>
                  <span>关键词筛选后数据量</span><br />
                  <span className='numStyle'>{this.state.keyWordHistoryTotal}</span>条
                </div>
              </div>
            </div>
            <div className='right_box right_two'>
              <div className='right_two_box right_two_margin'>
                <div>朋友圈数据（条）</div>
                <div className='numOne'>{this.state.friendTotal}</div>
                <div className='numTwo'>{this.state.focusMemberTotal}</div>
                <div>重点人数据（条）</div>
                <div className='zhanbi'>重点人占比 <span>{(this.state.focusMemberTotal/this.state.friendTotal).toFixed(2) * 100}</span>%</div>
              </div>
              <div className='right_two_box'>
                <div>微信群数据（条）</div>
                <div className='numOne'>{this.state.groupTotal}</div>
                <div className='numTwo'>{this.state.focusGroupTotal}</div>
                <div>重点组织数据（条）</div>
                <div className='zhanbi'>重点组织占比 <span>{(this.state.focusGroupTotal/this.state.groupTotal).toFixed(3) * 100}</span>%</div>
              </div>
            </div>
            <div id='bottomRightBottom' className='right_box_bottom'>
            </div>
          </div>
        </div>

      </div>
    )
  }
}

export default DataStatistics